//  很多需求的时候，没有写过,就大致分析一下过程。写的过程优化
const PENDING = "PENDING";
const FULFILLED = "FULFILLED";
const REJECTED = "REJECTED";

const resolvePromise = (promise, x, resolve, reject) => {
  console.log("promise", promise);
  debugger;
  if (promise === x) {
    reject("返回了当前同样的引用错误");
  }
  if (x !== null && (typeof x === "function" || typeof x === "object")) {
    try {
      const then = x.then;
      //   则认为返回了一个promise
      if (typeof then === "function") {
        then.call(
          x,
          (y) => {
            resolvePromise(promise2, y, resolve, reject);
          },
          (err) => {
            reject(err);
          }
        );
      } else {
        resolve(x);
      }
    } catch (error) {
      reject(error);
    }
  } else {
    resolve(x);
  }
};

class IPromise {
  constructor(executor) {
    this.state = PENDING;
    this.reason = undefined;
    this.value = undefined;
    // 异步
    this.onResolvedCallbacks = [];
    this.onRejectedCallbacks = [];
    let resolve = (value) => {
      this.value = value;
      this.state = FULFILLED;
      this.onResolvedCallbacks.forEach((fn) => {
        fn();
      });
    };

    let reject = (reason) => {
      this.reason = reason;
      this.state = REJECTED;
      this.onRejectedCallbacks.forEach((fn) => {
        fn();
      });
    };

    try {
      executor(resolve, reject);
    } catch (error) {
      reject(error);
    }
  }

  //   then 的作用只是用来执行回调函数，如果是异步函数，则将其存储，后改变状态，再执行
  then(onFulfilled, onRejected) {
    debugger;
    onFulfilled = typeof onFulfilled === "function" ? onFulfilled : (x) => x;
    onRejected = typeof onRejected === "function" ? onRejected : (err) => err;
    console.log(typeof onFulfilled === "function");
    let promise2 = new IPromise((resolve, reject) => {
      console.log(this.state);
      if (this.state === FULFILLED) {
        let x = onFulfilled(this.value);
        console.log(onFulfilled, promise2);
        // resolvePromise(promise2, x, resolve, reject);
      }

      if (this.state === REJECTED) {
        let x = onRejected(this.value);
        resolvePromise(promise2, x, resolve, reject);
      }

      if (this.state === PENDING) {
        this.onResolvedCallbacks.push(() => {
          let x = onFulfilled(this.value);
          resolvePromise(promise2, x, resolve, reject);
        });

        this.onRejectedCallbacks.push(() => {
          let x = onRejected(this.value);
          resolvePromise(promise2, x, resolve, reject);
        });
      }
    });

    return promise2;
  }
}

const promise = new IPromise((resolve, reject) => {
  setTimeout(() => {
    resolve("完成");
  }, 1000);
  // reject("失败");
  // resolve("完成");
})
  .then(
    (res) => {
      console.log(res);
      // 并不能直接调用(即使static)。
      debugger;
      return { name: "1123" };
    },
    (reason) => {
      console.log(reason);
    }
  )
  .then()
  .then((res) => {
    console.log("结果", res);
  });
